import { NestFactory } from '@nestjs/core'
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger'
import * as mongoose from 'mongoose'
import { NestExpressApplication } from '@nestjs/platform-express'
import { ValidationPipe } from '@nestjs/common'
import { join } from 'path'
import { AppModule } from './app.module'
import { CommonRespose } from './common/response'
import { HttpFilter } from './common/filter'

// const DB_URL = 'mongodb://localhost:27017'
const DB_URL = 'mongodb://127.0.0.1:27017'
const DB_NAME = 'contractManagement'

async function bootstrap() {
  await mongoose.connect(DB_URL, { dbName: DB_NAME })
  //如果配置静态资源，增加泛型NestExpressApplication
  const app = await NestFactory.create<NestExpressApplication>(AppModule)

  //配置 Swagger
  const config = new DocumentBuilder()
    .addBearerAuth() // 开启 BearerAuth 授权认证
    .setTitle('contract_servce')
    .setDescription('jckj合同管理平台')
    .setVersion('1.0')
    .build()
  const document = SwaggerModule.createDocument(app, config)
  SwaggerModule.setup('api-docs', app, document)

  //全局响应拦截器
  //统一相应拦截，返回给前端数据的统一格式
  app.useGlobalInterceptors(new CommonRespose())
  //全局异常过滤器
  app.useGlobalFilters(new HttpFilter())
  //全局管道，进行验证及转换
  app.useGlobalPipes(new ValidationPipe())

  // 使用静态资源
  app.useStaticAssets(join(__dirname, '..', 'public'), {
    prefix: '/static/', //设置虚拟路径
  }) //配置静态资源

  await app.listen(3000)
  console.log(`http://localhost:3000/api-docs`)
}
bootstrap()
